package tr.com.netgis;

import java.text.SimpleDateFormat;
import java.util.List;

import tr.com.netgis.log.LogArrayAdapter;
import tr.com.netgis.pojo.NGLocation;
import tr.com.netgis.util.Constants;
import tr.com.netgis.util.Utility;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;

/**
 * First main view of the application, after splash screen
 * 
 * @author NetGis
 * 
 */
public class MainActivity extends NGListActivity {

	private static final String TAG = MainActivity.class.getSimpleName();

	private ListView logList;
	// private TextView logView;
	// private Button btnLogViewClear;

	private List<NGLocation> listItems = null;
	private LogArrayAdapter adapter;
	private IMTSServiceApi api;
	private View uiConnectingToServiceView;
	private Handler handler;
	private ImageView imgGpsNotActive;
	final SimpleDateFormat SDF = Utility.createSimpleDateFormat();
	static OverlayItem _overItem;

	private MTSServiceConnection serviceConnection;

	private boolean mReceiversRegistered = false;
	private final ProviderChangedBroadcastReceiver mIntentReceiver = new ProviderChangedBroadcastReceiver(this, new Runnable(){
		@Override
		public void run() {
			MainActivity act = (MainActivity)mIntentReceiver.getContext();
	    	if (Utility.isGPSEnabled(act)) {
		    	act.imgGpsNotActive.setVisibility(View.INVISIBLE);		    		
	    	} else {
		    	act.imgGpsNotActive.setVisibility(View.VISIBLE);		    				    		
	    	}			
		}
		
	});
	
	private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i(TAG, "Received UPDATE_UI message");
			adapter.setLocations(mHelper.listLoggedLocations());
			adapter.notifyDataSetChanged();
		}
	};

	
	private IMTSServiceListener.Stub collectorListener = new IMTSServiceListener.Stub() {
		@Override
		public void handleLocationsUpdated() throws RemoteException {
			updateLogView();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		Runnable serviceBindCallback = new Runnable() {
			@Override
			public void run() {
				synchronized (serviceConnection) {
					api = serviceConnection.getServiceIfBound();
					try {
						if (api != null) {
							api.addListener(collectorListener);
						}
					} catch (RemoteException e) {
						Log.e(TAG, "Failed to add listener", e);
					}
					if (uiConnectingToServiceView != null
							&& uiConnectingToServiceView.getParent() != null) {
						((LinearLayout) uiConnectingToServiceView.getParent())
								.removeView(uiConnectingToServiceView);
					}
					updateLogView();
					Log.i(TAG, "Starting recording");
				}
			}
		};
		
		//serviceConnection = new MTSServiceConnection(this, serviceBindCallback);
		setupActivity();
		startService(Constants.MTS_SERVICE_INTENT);

		//serviceConnection.startAndBind();
		Log.i(TAG, "Activity created");
	}

	protected void setupActivity() {
		handler = new Handler(); // handler will be bound to the current thread
		// logView = (TextView) findViewById(R.id.logView);
		logList = (ListView) findViewById(R.id.logList);

		listItems = mHelper.listLoggedLocations();
		adapter = new LogArrayAdapter(this, listItems);
		logList.setAdapter(adapter);
		
		uiConnectingToServiceView = (View) findViewById(R.id.mainLayoutIUConnectingToService);
		imgGpsNotActive = (ImageView) findViewById(R.id.mainImgGpsNotActive);

		logList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {

				final NGLocation location = (NGLocation) arg0
						.getItemAtPosition(arg2);
				final CharSequence[] items = { "Ayrıntı", "Harita" };

				AlertDialog.Builder builder = new AlertDialog.Builder(
						MainActivity.this);
				builder.setTitle("İşlem");
				builder.setItems(items, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int item) {
						if (item == 1) {
							Toast.makeText(getApplicationContext(),
									location.toString(), 4).show();
							GeoPoint p = new GeoPoint(
									(int) (location.getLat() * 1e6),
									(int) (location.getLon() * 1e6));
							showMap(p);
						} else if (item == 0) {
							showLocationDetail(location);
						}
					}
				});
				AlertDialog alert = builder.create();
				alert.show();
				return true;
			}

		});

		/*
		 * btnLogViewClear.setOnClickListener(new OnClickListener() {
		 * 
		 * @Override public void onClick(View v) {
		 * listItems.removeAll(listItems); adapter.notifyDataSetChanged(); } });
		 */

		// start the service explicitly.
		// otherwise it will only run while the IPC connection is up.

		/*
		 * startService(Constants.SET_LOCATION_SERVICE_INTENT);
		 * bindService(Constants.SET_LOCATION_SERVICE_INTENT, serviceConnection,
		 * 0);
		 */
	}

	@Override
	protected void onStart() {
		Log.d(TAG, "MainActivity.onStart");
		super.onStart();
	}

	@Override
	protected void onDestroy() {
		try {
			uiConnectingToServiceView = null;
			//api.removeListener(collectorListener);
			//serviceConnection.unbind();
		} catch (Throwable t) {
			Log.w(TAG, "Failed to unbind from the service", t);
		}
		Log.i(TAG, "Activity destroyed");
		super.onDestroy();
		// Utility.killApp(true);
	}

	private void updateLogView() {

		handler.post(new Runnable() {
			@Override
			public void run() {
				try {
					if (api == null) {
						return;
					}
					MTSServiceResult result = api.getResult();
					Log.i("LOCATION SERVICE", "Handler " + result.getmData());
					if (result.getLocation() == null) {
						;
					} else {
						// provider = result.getmData();
						Log.d("ARRAYADAPTER: ", result.getLocation().toString());
						listItems.add(0, result.getLocation());
						adapter.notifyDataSetChanged();
						FileLogger.log(result.getLocation().toString().trim());
					}
				} catch (Throwable t) {
					Log.e(TAG, "Error while updating the UI with locations", t);
				}
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = this.getMenuInflater();
		inflater.inflate(R.menu.menu, menu);

		super.onCreateOptionsMenu(menu);
		return true;
	}

	private void showMessages() {
		Intent intent = new Intent(this, MessagesListActivity.class);
		startActivity(intent);
	}

	private void showSettings() {
		Intent settingsActivity = new Intent(this, Preferences.class);
		startActivity(settingsActivity);
	}

	private void showNotPostedList() {
		Intent act = new Intent(this, NotPostedLocationListActivity.class);
		startActivity(act);
	}

	/**
	 * Quits all program end stops the background mts service
	 */
	private void quit() {
		try {
			// stopService(Constants.SET_LOCATION_SERVICE_INTENT);
			serviceConnection.stop();
		} catch (Throwable t) {
			Log.w(TAG, "Failed to stop service", t);
		}
		this.finish();
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		/*
		 * case R.id.menu_about: showAbout(); return true;
		 */
		case R.id.menu_settings:
			showSettings();
			return true;
			/*
			 * case R.id.menu_filelog: showFileLog(); return true;
			 */
		case R.id.menu_quit:
			quit();
			return true;
		case R.id.menu_notposted:
			showNotPostedList();
			return true;
		case R.id.menu_messages:
			showMessages();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private void showMap(GeoPoint point) {
		MapViewActivity.setGeoPoint(point);
		Intent mapActivity = new Intent(this, MapViewActivity.class);
		startActivity(mapActivity);
	}

	private void showLocationDetail(NGLocation location) {
		Intent detail = new Intent(this, LocationViewActivity.class);
		detail.putExtra("location", location);
		startActivity(detail);
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.d(TAG, "MainActivity.onResume");
		
		
		
		IntentFilter intentToReceiveFilter = new IntentFilter();
		intentToReceiveFilter.addAction("android.location.PROVIDERS_CHANGED");
		this.registerReceiver(mIntentReceiver, intentToReceiveFilter);

		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction("tr.com.netgis.UPDATE_UI");
		this.registerReceiver(this.broadcastReceiver, intentFilter);
		//getCursorAdapter().getCursor().requery();
		adapter.notifyDataSetChanged();
		
		mReceiversRegistered = true;
	
		//serviceConnection.bindIfRunning();
	}
	
	@Override
	public void onPause() {
		super.onPause();

		if(mReceiversRegistered) {
			this.unregisterReceiver(mIntentReceiver);
			this.unregisterReceiver(broadcastReceiver);
			mReceiversRegistered = false;
		}
	}


}